package com.zhihaoliang.moshi.biz.adapter

import com.squareup.moshi.*
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import com.zhihaoliang.moshi.util.log


/**
 * @author 支豪亮
 * @date 2023/1/28 16:25
 */

fun customAdapterWithDelegate() {
    val data = """
  [
    {
        "name":"not-started"
    },
    {
        "name":"in-progress"
    },
    {
        "name":"in-progress2"
    },
    {
        "name":"rejected"
    },
    {
        "name":"completed"
    }
]
    """.trimIndent()

    val moshi = Moshi.Builder().add(StageAdapter()).add(KotlinJsonAdapterFactory()).build()
    val jsonAdapter = moshi.adapter<List<StageEle>>(
        Types.newParameterizedType(
            List::class.java,
            StageEle::class.java
        )
    )
    log(jsonAdapter.fromJson(data).toString())
}


class StageAdapter {
    @FromJson
    fun fromJson(jsonReader: JsonReader, delegate: JsonAdapter<Stage>): Stage {
        val value = jsonReader.nextString()

        return if (value.startsWith("in-progress")) {
            Stage.IN_PROGRESS
        } else {
            delegate.fromJsonValue(value) ?: Stage.IN_PROGRESS
        }
    }
}

enum class Stage {
    @Json(name = "not-started") NOT_STARTED, @Json(name = "in-progress") IN_PROGRESS,
    @Json(name = "rejected") REJECTED, @Json(name = "completed") COMPLETED
}

data class StageEle(val name: Stage)